package com.linkface.liveness.network;

import android.content.Context;
import android.text.TextUtils;
import android.webkit.DownloadListener;

import com.alibaba.fastjson.JSON;
import com.linkface.liveness.LFLivenessSDK;
import com.linkface.liveness.util.LFLog;
import com.linkface.liveness.util.LFSDCardUtils;
import com.linkface.liveness.util.MD5Util;

import java.io.File;

/**
 * Created by yuemq on 2018/9/10.
 */

public class LFLiDownloadManager {
    private static String TAG = LFLiDownloadManager.class.getSimpleName();
    private static LFLiDownloadManager instance;
    private final Context mContext;

    private LFLiDownloadManager(Context context) {
        mContext = context;
    }

    public static LFLiDownloadManager getInstance(Context context) {
        if (instance == null) {
            synchronized (LFLiDownloadManager.class) {
                if (instance == null) {
                    instance = new LFLiDownloadManager(context);
                }
            }
        }
        return instance;
    }

    private LFLicenceModel licResult;

    /**
     * 下载最新License文件
     *
     * @param license_info_url 更新License的链接
     * @param listener 下载监听
     */
    public void downLoadLic(String license_info_url, DownloadListener listener) {
        this.listener = listener;
        LFGetRequestUtils.getRequest(license_info_url, new LFNetRequestCallback() {
            @Override
            public void completed(String response) {
                if (!TextUtils.isEmpty(response)) {
                    licResult = JSON.parseObject(response, LFLicenceModel.class);
                    if (licResult != null)
                        downLoadLicContent(licResult.lic_url, licResult.md5);
                    else
                        setResult(false, "服务器返回lic信息为空");
                } else {
                    setResult(false, "服务器返回lic信息为空");
                }
            }

            @Override
            public void failed(int httpStatusCode, String error) {
                super.failed(httpStatusCode, error);
                setResult(false, "error:" + error);
                LFLog.i(TAG + "code:" + httpStatusCode + ";error:" + error);
            }
        });
    }

    private void downLoadLicContent(String url, final String md5) {
        LFGetRequestUtils.getRequest(url, new LFNetRequestCallback() {
            @Override
            public void completed(String response) {
                LFLog.i(TAG + "response:" + response);
                String md5Resp = MD5Util.MD5(response);
                if (TextUtils.equals(md5,md5Resp)) {
                    //保存license内容
                    saveLicFile(response);
                } else {
                    setResult(false, "md5校验失败");
                    LFLog.i(TAG + "md5校验失败");
                }
            }

            @Override
            public void failed(int httpStatusCode, String error) {
                super.failed(httpStatusCode, error);
                setResult(false, "md5校验失败");
            }
        });
    }

    private void saveLicFile(final String response) {
        String licPath = LFLivenessSDK.getInstance(mContext).getLicPath();
        if (TextUtils.isEmpty(licPath)) {
            return;
        }
        String[] licPathSplit = licPath.split(File.separator);
        String licName = licPathSplit[licPathSplit.length - 1];
        File appFilesFile = mContext.getFilesDir();
        licPath = appFilesFile.getAbsolutePath() + File.separator + licPath;
        File licFile = new File(licPath);
        String copyLicPath = "";
        if (licFile.exists()) {
            //licFile存在时，说明已经更新过license，并且license再次过期
            //此时将licPath目录下oldLicense备份到temp下，然后删掉oldLicense，将下载的newLicense保存到licPath目录下
            String copyLicDirectory = licFile.getParent() + File.separator + "temp";
            copyLicPath = copyLicDirectory + File.separator + licName;
            boolean copySuccess = LFSDCardUtils.copyFile(licPath, copyLicPath);
            if (copySuccess) {
                boolean deleteSuccess = licFile.delete();
                if (deleteSuccess) {
                    boolean saveSuccess = LFSDCardUtils.saveFile(licFile, response);
                    if (!saveSuccess) {
                        //如果保存失败，则需将备份还原
                        LFSDCardUtils.copyFile(copyLicPath, licPath);
                        setResult(false, "替换失败");
                    } else {
                        setResult(true, "下载并替换成功");
                    }
                    //删除temp文件夹
                    LFSDCardUtils.deleteFile(new File(copyLicDirectory));
                } else {
                    setResult(false, "替换失败");
                }
            } else {
                setResult(false, "替换失败");
            }
        } else {
            //licFile不存在时，直接将下载的newLicense保存到licPath目录下
            if (LFSDCardUtils.saveFile(licFile, response)) {
                setResult(true, "下载并保存成功");
            } else {
                setResult(false, "保存失败");
            }
        }
    }

    private void setResult(boolean isSuccess, String errorMsg) {
        if (listener != null) {
            listener.onDownload(isSuccess, errorMsg);
        }
    }

    private DownloadListener listener;

    public interface DownloadListener {
        void onDownload(boolean isSuccess, String errorMsg);
    }
}
